package com.example.concurrentprogramming8016.reetrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyanhao
 * @Date 2023-01-07 20:18
 * lockInterruptibly
 * lock
 * 两者主要的区别是
 * lockInterruptibly 竞争获取锁的时候如果被中断会立刻抛出异常 可以catch 执行一些操作
 * lock 会在获得到锁后才会执行中断的操作
 */
public class LockInterruptiblyDemo {
    private ReentrantLock lock = new ReentrantLock();

    public void doSomeThing() {
        String name = Thread.currentThread().getName();
        System.out.println("尝试获取锁:" + name);
        try {
            lock.lockInterruptibly();
            System.out.println(name + " 得到锁");
            System.out.println(name + " 开工干活");
            for (int i = 0; i < 5; i++) {
                TimeUnit.SECONDS.sleep(5);
                System.out.println(name + " :" + i);
            }
        } catch (InterruptedException e) {
            System.out.println("被中断了");
            System.out.println("做一些别的事情");
        } finally {

            try {
                lock.unlock();
                System.out.println("释放锁成功" + name);
            } catch (Exception e) {
                System.out.println(name + "没有得到锁的线程运行结束" + e);
            }

        }


    }

    public static void main(String[] args) throws InterruptedException {
        LockInterruptiblyDemo lockInterruptiblyDemo = new LockInterruptiblyDemo();
        Thread thread = new Thread(() -> {
            lockInterruptiblyDemo.doSomeThing();
        }, "thread-1");
        thread.start();
        TimeUnit.SECONDS.sleep(6);
        Thread thread2 = new Thread(() -> {
            lockInterruptiblyDemo.doSomeThing();
        }, "thead-2");
        thread2.start();
        thread2.interrupt();


    }
}
